package com.bgrconsulting.stockorderentry.service.rest.impl;

import java.util.Date;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import com.bgrconsulting.stockorderentry.service.converter.PlaceEquityOrderConverter;
import com.bgrconsulting.stockorderentry.service.converter.PreviewEquityOrderConverter;
import com.bgrconsulting.stockorderentry.service.converter.response.PlaceEquityOrderResponseConverter;
import com.bgrconsulting.stockorderentry.service.dao.PlaceEquityOrderResponseDao;
import com.bgrconsulting.stockorderentry.service.dao.PreviewEquityOrderResponseDao;
import com.bgrconsulting.stockorderentry.service.model.response.PlaceEquityOrderResponse;

@Path("/order/rest/placeequityorder/")
public class PlaceEquityOrderResource {
	@Context
	UriInfo uriInfo;
	@Context
	Request request;
	String id;
	/*public PreviewEquityOrderResource(UriInfo uriInfo, Request request, String id) {
		this.uriInfo = uriInfo;
		this.request = request;
		this.id = id;
	}*/
	
	//Application integration 		
	@GET
	@Path("/{orderId}") 
	@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
	public PlaceEquityOrderResponseConverter getPlaceEquityOrderResponse(@PathParam ("orderId") String orderId) {
		PlaceEquityOrderResponseConverter placeEquityOrderReqponse = PlaceEquityOrderResponseDao.instance.getModel().get(orderId);
		if(placeEquityOrderReqponse==null)
			throw new RuntimeException("Get: Placed equity order with " + orderId +  " not found");
		return placeEquityOrderReqponse;
	}

	@POST
    @Consumes({"application/xml","application/json"})
    public Response createNewPlaceEquityOrder(JAXBElement<PlaceEquityOrderConverter> placeEquityOrder) {
        
		PlaceEquityOrderResponse placeEquityOrderResponse = new PlaceEquityOrderResponse();
		
	
		PlaceEquityOrderResponseConverter peorc = new PlaceEquityOrderResponseConverter(placeEquityOrderResponse);
		
		return putAndGetResponse(peorc);
		
    }
	
	private Response putAndGetResponse(PlaceEquityOrderResponseConverter placeEquityOrderResponse) {
		Response res;
		if(PlaceEquityOrderResponseDao.instance.getModel().containsKey(placeEquityOrderResponse.getEquityOrderResponse().getAccountId())) {
			res = Response.noContent().build();
		} else {
			res = Response.created(uriInfo.getAbsolutePath()).build();
		}
		PlaceEquityOrderResponseDao.instance.getModel().put(placeEquityOrderResponse.getEquityOrderResponse().getAccountId(), placeEquityOrderResponse);
		return res;
	}
}

